package org.spbsu.squaddie.adapter.csv;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.spbsu.squaddie.model.Cell;
import org.spbsu.squaddie.model.Event;
import org.spbsu.squaddie.model.Snapshot;
import org.spbsu.squaddie.model.TimeSerie;

import au.com.bytecode.opencsv.CSVReader;

public class Scanner {
	private static final String SUSPENDED_FLAG = "SUSPENDED";
	private static final Integer MARKET_STATUS_INDEX = 2;
	private static final Integer SELECTION_ID_INDEX = 3;
	private static final Integer LINES_IN_HEADER = 3;

	public List<TimeSerie> scanFolder(String folderName) {

		List<TimeSerie> result = new ArrayList<>();

		File folder = new File(folderName);

		if (!folder.isDirectory()) {
			System.out.println("The file is not a folder.");
			return result;
		}

		for (File file : folder.listFiles()) {
			if (file.isFile() && !file.isHidden()) {
				TimeSerie timeSerie = getTimeSerie(file);

				result.add(timeSerie);
			}
		}

		return result;
	}

	public TimeSerie getTimeSerie(File seriesFile) {
		List<String[]> lines = new ArrayList<>();

		CSVReader reader = null;
		try {
			reader = new CSVReader(new FileReader(seriesFile));
			String[] nextLine;

			while ((nextLine = reader.readNext()) != null) {
				lines.add(nextLine);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return parseLines(lines.subList(LINES_IN_HEADER, lines.size() - 1));
	}

	private TimeSerie parseLines(List<String[]> lines) {

		if (lines == null || lines.isEmpty()) {
			System.out.println("Error parseLines(): invalid input.");
			return TimeSerie.getEmpty();
		}

		TimeSerie timeSerie = new TimeSerie();
		List<String[]> snapshotString = new ArrayList<>();
		String beginner = lines.get(0)[SELECTION_ID_INDEX];

		for (String[] line : lines) {

			if (line[MARKET_STATUS_INDEX].equals(SUSPENDED_FLAG)) {
				break;
			}

			if (line[SELECTION_ID_INDEX].equals(beginner)) {
				if (!snapshotString.isEmpty()) {
					timeSerie.add(parseSnapshot(snapshotString));
				}
				snapshotString = new ArrayList<>();
				beginner = line[SELECTION_ID_INDEX];
			}

			snapshotString.add(line);
		}

		return timeSerie;
	}

	private Snapshot parseSnapshot(List<String[]> snapshot) {
		Snapshot result = new Snapshot();

		for (String[] eventString : snapshot) {
			result.add(parseEvent(eventString));
		}

		return result;
	}

	private Event parseEvent(String[] eventString) {
		Event event = new Event();

		Cell left = new Cell(Double.parseDouble(eventString[5]),
				Double.parseDouble(eventString[6]));
		Cell right = new Cell(Double.parseDouble(eventString[7]),
				Double.parseDouble(eventString[8]));

		event.add(left);
		event.add(right);

		return event;
	}
}
